package org.iiitb.assignment.wizards;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Calendar;

import org.eclipse.jface.wizard.Wizard;
import org.iiitb.assignment.extension.MainView;

public class WizardMain extends Wizard {

	Connection con = null;
	String url = "jdbc:mysql://localhost:3306/";
	String db = "travel_world";
	String driver = "com.mysql.jdbc.Driver";
	String username = "root";
	String password = "root";


	protected WScreenOne one;
	protected WScreenTwo two;
	protected WScreenThree three;
	private String result;
	MainView view;

	public String getResult() {
		return result;
	}

	public WizardMain(MainView v) {
		super();
		setNeedsProgressMonitor(true);

		try{
			Class.forName(driver).newInstance();
			con = DriverManager.getConnection(url+db,username,password);
		}catch(Exception e){
			e.printStackTrace();
		}
		view = v;
	}

	@Override
	public void addPages() {
		one = new WScreenOne();
		two = new WScreenTwo();
		three = new WScreenThree();
		addPage(one);
		addPage(two);
		addPage(three);
	}

	@Override
	public boolean performFinish() {
		// Print the result to the console
		Calendar c = three.getTravelDate();

		result = "Travel Name : "+ one.getTravelName();
		result += "\n" + ("Details : "+two.getFrom()+" to "+two.getTo());
		if(!two.getVia1().isEmpty()&&!two.getVia2().isEmpty()&&!two.getVia3().isEmpty()){
			result += " via ";
			result += two.getVia1()+" "+two.getVia2()+" "+two.getVia3();
		}
		result += "\n"+("Agent : "+three.getTravelAgent());
		result += "\n"+("Date : "+c.get(Calendar.DATE)+"-"+(c.get(Calendar.MONTH)+1)+"-"+c.get(Calendar.YEAR));


		String query = "INSERT INTO travel_world.travel_details (tname, from_place, to_place, via1, via2, via3, agent_name, tdate) " +
				"VALUES ( '"+one.getTravelName()+"', '"+two.getFrom()+"', '"+two.getTo()+"', '"+
				two.getVia1()+"', '"+two.getVia2()+"', '"+two.getVia3()+"', '"+
				three.getTravelAgent()+"', '"+c.get(Calendar.YEAR)+"-"+(c.get(Calendar.MONTH)+1)+"-"+c.get(Calendar.DATE)+"');";//2012-12-09');

		System.out.println(query);
		int ret = 0;
		try{
			Statement st = con.createStatement();
			ret = st.executeUpdate(query);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		if(ret ==1)
			view.updateResult(result+"\n\nSuccessfully Inserted");
		else
			view.updateResult(result+"\n\nError in Insertion.");


			return true;
	}
} 